import axios from 'axios';
import JSZip from 'jszip';
import { Sitdown } from 'sitdown'
import { TmpFile } from './converter';
import localforage from 'localforage';
import { saveAs } from 'file-saver'
let sitdown = new Sitdown({
  keepFilter: ['style'],
  codeBlockStyle: 'fenced',
  bulletListMarker: '-',
  hr: '---',
});
enum BlockType {
  page = 'page',//
  text = 'text',       //
  h1 = 'heading1',         //
  h2 = 'heading2',         //
  h3 = 'heading3',         //
  h4 = 'heading4',         //
  h5 = 'heading5',             //
  h6 = 'heading6',             //
  h7 = 'heading7',             //
  h8 = 'heading8',             //
  h9 = 'heading9',             //
  bullet = 'bullet',    //
  orderList = 'orderList',      //
  code = 'code',           //
  ref = 15,       //
  equation,
  todo = 'todo',           //
  bitable = 19,
  callout,
  chat_card,
  diagram,
  divider,           //
  file = 23,
  grid,            //
  grid_column,       //
  iframe,
  image = 'image',          //
  widget = 29,
  mindnote,
  sheet,
  table,
  tabel_cell,
  view,
  // ----
  quote = 'quote_container',     //
  unsupport = 999
}
let index = 0

let renderBullet: string[] = []
async function converBlock(md: string,block: any,zip: JSZip,blockId: string,blockMap: any,parent_prefix?: string) {
  const { data: blockData,id } = block
  const { type,text,image,done, children } = blockData
  console.log("🚀 ~ converBlock ~ type:",type, blockData)
  switch (type) {
    case BlockType.page:
      md += `# ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.text:
        console.log('renderBullet======>',renderBullet, id)
      if (renderBullet.includes(id)) {
        md += `${parent_prefix ? parent_prefix : ''}> `
        console.log('renderBullet======>',md)
      }
      md += `${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h1:
      md += `# ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h2:
      md += `## ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h3:
      md += `### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h4:
      md += `#### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h5:
      md += `##### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h6:
      md += `###### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h7:
      md += `####### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h8:
      md += `######## ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.h9:
      md += `######### ${text.initialAttributedTexts.text[0]}\n`
      break
    case BlockType.todo:
      if (done) {
        md += `- [x] ${text.initialAttributedTexts.text[0]}\n`
      } else {
        md += `- [ ] ${text.initialAttributedTexts.text[0]}\n`
      }
      break
    case BlockType.bullet:
      md += `${parent_prefix ? parent_prefix : ''}* ${text.initialAttributedTexts.text[0]}\n`
      if (children) {
        for (let i = 0; i < children.length; i++) {
          if (renderBullet.includes(children[i])) {
            continue
          }
          renderBullet.push(id)
          await converBlock(md,blockMap[children[i]],zip,children[i],blockMap,"")
        }
      }
      break
    case BlockType.orderList:
      break
    case BlockType.code:
      break
    case BlockType.quote:
      console.log(blockData,'image',id)
      if (children) {
        for (let i = 0; i < children.length; i++) {
          if (renderBullet.includes(children[i])) {
            continue
          }
          renderBullet.push(children[i])
          await converBlock(md,blockMap[children[i]],zip,children[i],blockMap,"> ")
        }
      }
      break
    case BlockType.image:
      const token = image.token
      const name = image.name
      const mimeType = image.mimeType
      const fileName = await downloadAsset(token,blockId,zip,name)
      md += `![](assets/${fileName})\n`
      break
  }
  return md
}
// https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/v2/cover/WP2SbluZxoLAQBxiW3LcWtGtnNe/?fallback_source=1&height=1280&mount_node_token=KgmtdKXxooOCeuxHeY9c4qtMnhe&mount_point=docx_image&policy=equal&width=1280
// https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/v2/cover/SpV0bXNOwoOo6TxNtivcvbCBn5g/?fallback_source=1&height=1280&mount_node_token=Xc6vdIqJDoeTmGxpm9ScUfyXnfd&mount_point=docx_image&policy=equal&width=1280
// https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/v2/cover/GRceb68A4oHFrCxCKp8cyztUn8f/?fallback_source=1&height=1280&mount_node_token=BND1d4MdkodcKpxr2q3ceG0InZe&mount_point=docx_image&policy=equal&width=1280
// https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/preview/MY6ubl5qBotoG2x1bfWc3ZnanGe/?preview_type=16
// blob:https://ry5hwpuf7b.feishu.cn/d8281a51-1116-4ee2-af04-1fb75c5a364d

const tmp = localforage.createInstance({
  name: 'file_cache'
})
async function downloadAsset(token: string,nodeToken: string,zip: JSZip,name?: string) {
  let c = await tmp.getItem<TmpFile>(token)
  let ext = { value: "" }
  function get_ext(mim: string) {
    const mtype = mim.split("/")
    if (mtype.length === 2) {
      ext.value = "." + mtype[1]
    } else {
      console.log(mtype)
    }
  }
  if (c) {
    let mime = c.mime
    get_ext(mime)
    zip.folder("assets")?.file(name ? (token + "_" + name) : (token + ext.value),c.data)
  } else {
    // const url = `https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/v2/cover/${token}/?fallback_source=1&height=1280&mount_node_token=${nodeToken}&mount_point=docx_image&policy=equal&width=1280`
    const url = `https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/preview/${token}/?preview_type=16`
    // console.log('🚀 ~ downloadAsset ~ url:', url)
    // let r = await axios.get(url,
    //     {
    //         responseType: 'arraybuffer',
    //         headers: {
    //           "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
    //           "Referer": "https://vliajwma3m.feishu.cn",
    //           "origin": "https://vliajwma3m.feishu.cn",
    //           Origin:"https://vliajwma3m.feishu.cn",
    //           "Sec-Ch-Ua": `"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"`,
    //           "Sec-Ch-Ua-Mobile":
    //           "?0",
    //           "Sec-Ch-Ua-Platform":
    //           "macOS"
    //         }
    //     })
    // let mime = r.headers['content-type']
    // get_ext(mime)

    const r = await fetch(url,{ mode: 'cors' }).then(res => res.blob()).then(blob => blob)
    const mime = r.type
    get_ext(mime)

    // return new Promise((resolve,reject) => {
    //   browser.downloads.download({
    //     url,
    //     filename: `_tmp/downloaded_file_${index}.jpg`,
    //     saveAs: false,
    //     conflictAction: 'overwrite',
    //   }).then((downloadId) => {
    //     browser.downloads.onChanged.addListener((delta) => {
    //       if (delta.id === downloadId && delta.state && delta.state.current === 'complete') {
    //         console.log('Download completed')
    //         browser.downloads.getFileIcon(downloadId).then((iconUrl) => {
    //           console.log(iconUrl)
    //         })
    //       }
    //     })
    //   })
    // })


    const result = await r.arrayBuffer()
    const data = new Uint8Array(result)
    zip.folder("assets")?.file(name ? (token + "_" + name) : (token + ext.value),data)
    await tmp.setItem(token,{
      mime: 'image/jpeg',
      data: data
    })
  }
  return name ? (token + "_" + name) : (token + ext.value)
}

export const convert = async (blockMap: any,queues: string[],title = '') => {
  console.log('🚀 ~ convert ~ blockMap:',blockMap,queues)
  index = 0
  let markdownContent = ''
  renderBullet = []
  const jsZip = new JSZip()

  for (let i = 0; i < queues.length; i++) {
    const block = blockMap[queues[i]]
    // console.log('🚀 ~ convert ~ block:',block)
    console.log('======', i)
    markdownContent = await converBlock(markdownContent,block,jsZip,queues[i],blockMap)
  }

  jsZip.file(`${title}.md`,markdownContent)

  jsZip.generateAsync({ type: "blob" }).then(function (content) {
    const reader = new FileReader()
    reader.readAsDataURL(content)

    reader.onloadend = function () {
      const base64data = reader.result
      browser.tabs.query({
        active: true,
        currentWindow: true
      }).then(tabs => {
        const tab = tabs[0]
        console.log("🚀 ~ tab:", tab)
        if (tab?.id) {
          browser.tabs.sendMessage(tab.id,{ action: 'downloadFile',data: base64data,name: `${title}.zip` }).then((res) => {
          console.log('Download ZIP completed')
        })
        }
      })
      //  browser.runtime.sendMessage({ action: 'downloadFile',data: base64data,name: `${title}.zip` }).then((res) => {
      //   console.log('Download ZIP completed')
      //  })

    }
  }).catch((err) => {
    console.log('Download ZIP err',err)
  })

  // jsZip.generateAsync({ type: "blob" }).then(function (content) {
  //   console.log(saveAs)
  //   saveAs(content,`${title}.zip`);
  //   const fileName = `${title}.zip`
  //   const blob = new Blob([content],{ type: 'application/zip' })

  //   // browser.downloads.download({
  //   //   url: url,
  //   //   filename: `${title}.zip`,
  //   //   saveAs: false,
  //   //   conflictAction: 'overwrite',
  //   // }).then((downloadId) => {
  //   //   console.log('Download ZIP completed')
  //   // }).catch((err) => {
  //   //   console.log('Download ZIP err',err)
  //   // })
  //   saveZipFile(blob)
  // }).catch((err) => {
  //   console.log('Download ZIP err',err)
  // })
  // console.log(markdownContent,'==============')
}

function saveZipFile(blob) {
  // 使用 chrome.runtime 创建一个 Blob URL
  const url = browser.runtime.getURL(blob);

  // 创建一个临时的 <a> 元素用于下载
  const downloadLink = document.createElement('a');
  downloadLink.href = url;
  downloadLink.download = 'my zipfile.zip'; // 指定下载文件的默认文件名

  // 将下载链接添加到文档中，并模拟点击以触发下载
  document.body.appendChild(downloadLink);
  downloadLink.click();

  // 清理：移除 <a> 元素
  document.body.removeChild(downloadLink);
}